var express = require("express");
var router = express.Router();

/* auth register page. */
router.get("/register", function (req, res, next) {
  res.render("auth/register.html");
});

router.post("/register", async (req, res) => {
  let error = "";
  const { username, password } = req.body;
  const db = req.app.locals.db;

  if (!username) {
    error = "Username is required.";
  } else if (!password) {
    error = "Password is required.";
  }

  const user = await new Promise((resolve, reject) => {
    db.get("SELECT * FROM user WHERE username = ?", [username], (err, row) => {
      if (err) {
        reject(err);
      }
      resolve(row);
    });
  });

  if (user) {
    error = "User " + username + " is already registered.";
  }

  if (error) {
    return res.render("auth/register.html", { message: error });
  } else {
    await db.run("INSERT INTO user (username, password) VALUES (?, ?)", [
      username,
      password,
    ]);
    res.redirect("/auth/login");
  }
});

/* auth login page. */
router.get("/login", function (req, res, next) {
  res.render("auth/login.html");
});

router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const db = req.app.locals.db;

  const user = await new Promise((resolve, reject) => {
    db.get(
      "SELECT * FROM user WHERE username = ? AND password = ?",
      [username, password],
      (err, row) => {
        if (err) {
          reject(err);
        }
        resolve(row);
      }
    );
  });

  if (user) {
    // 用户存在且密码匹配
    req.session.user = user; // 这里你也需要确保session是配置好的
    res.redirect("/");
  } else {
    // 用户不存在或密码不匹配
    res.render("auth/login.html", { message: "Invalid username or password" });
  }
});

router.get("/logout", (req, res) => {
  req.session.destroy();
  res.redirect("/auth/login");
});

module.exports = router;
